package com.study.controller;

import com.study.entity.PermissionVo;
import com.study.entity.User;
import com.study.service.PermissionService;
import com.study.service.UserService;
import com.study.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login() {
        return "redirect:/login.jsp";
    }

    /*@RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String userName, String userPwd, HttpServletRequest request) {
        // 访问数据库
        if (userService.contains(userName, MD5Util.MD5Encryption(userPwd)) == 1) {
            HttpSession session = request.getSession();
            session.setAttribute("userInfo", userService.findUserInfoByName(userName));
            return "redirect:/app";
        }
        return "redirect:/login.jsp";
    }*/

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public String login(HttpServletRequest request) {
        String loginName = request.getParameter("loginName");
        String loginPwd = request.getParameter("loginPwd");

        // 访问数据库
        if (userService.contains(loginName, MD5Util.MD5Encryption(loginPwd)) == 1) {
            HttpSession session = request.getSession();
            session.setAttribute("userInfo", userService.findUserInfoByName(loginName));
            return "true";
        }
        return "false";
    }


    @RequestMapping(value = "/app")
    public ModelAndView menu(HttpSession session) {
        ModelAndView mv = new ModelAndView();
        if (session != null && session.getAttribute("userInfo") != null) {
            // 查询该用户权限
            User user = (User) session.getAttribute("userInfo");
            Integer userId = user.getUserId();
            List<PermissionVo> permissionVos = permissionService.getCatalogIdByUserId(userId);
            mv.addObject("permissionVos", permissionVos);
            mv.setViewName("main");
            return mv;
        }
        mv.setViewName("forward:/login.jsp");
        return mv;
    }

    @RequestMapping(value = "/welcome",method = RequestMethod.GET)
    public String welcome() {
        return "welcome";
    }
}
